package br.com.localfloripa.handlers;

import java.io.IOException;

import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import br.com.localfloripa.entities.Usuario;

@Named("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
	
	private static final String HOME_ADMIN = "/admin/home.xhtml";
	private static final String HOME_CLIENT = "/admin/home.xhtml";
	private static final String HOME_IMOVEIS = "/admin/home.xhtml";
	private static final String HOME_CONCESSIONARIAS = "/admin/home.xhtml";
	private static final String PAGE_ERROR = "/admin/error.xhtml";

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication auth) throws IOException,ServletException {
		
		if (auth.isAuthenticated() && Usuario.hasRole("ADMIN")) {		
			response.sendRedirect(request.getContextPath() + HOME_ADMIN);			
		} else if (auth.isAuthenticated() && Usuario.hasRole("CLIENTE")) {
			response.sendRedirect(request.getContextPath() + HOME_CLIENT);
		} else if (auth.isAuthenticated() && (Usuario.hasRole("IMOBILIARIA") || Usuario.hasRole("CORRETOR"))) {
			response.sendRedirect(request.getContextPath() + HOME_IMOVEIS);
		}else if (auth.isAuthenticated() && Usuario.hasRole("CONCESSIONARIA")) {
			response.sendRedirect(request.getContextPath() + HOME_CONCESSIONARIAS);
		} else {
			response.sendRedirect(request.getContextPath() + PAGE_ERROR);
		}

	}

}
